package com.hcmiu.buddytracking;

import getFromDBMethods.getAllPOIs;

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import setMethods.deletePOI;
import setMethods.setPOIStatus;
import Storage.POI;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class POIList extends ListActivity {
	private ArrayList<POI> poilist = new ArrayList<POI>();
	private POIAdapter myAdapter;
	private SharedPreferences pref;
	private String PREF_NAME = "buddytracking";
	private String currentPhoneNumber;
	private ProgressDialog progressDialog;
	private LocationManager locMgr = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.poilist);

		pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
		currentPhoneNumber = pref.getString("currentPhoneNumber", null);
		locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Please wait...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);

		myAdapter = new POIAdapter(this, R.layout.onepoi, poilist);
		setListAdapter(myAdapter);

		registerForContextMenu(getListView());

		progressDialog.show();
		getPOIList();

	}

	private void getPOIList() {
		Thread t = new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				try {
					poilist = getAllPOIs.process(currentPhoneNumber);
					for (int i = 0; i < poilist.size(); i++) {
						if (!poilist.get(i).getMarkerPhoneNo().equals(
								currentPhoneNumber)
								&& poilist.get(i).getIsHidden().equals("1")) {
							poilist.remove(i);
							i--;
						}
					}
					runOnUiThread(returnRes);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				Looper.loop();
			}
		};
		t.start();
	}

	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			if (poilist != null && poilist.size() > 0) {
				myAdapter.notifyDataSetChanged();
				for (int i = 0; i < poilist.size(); i++) {
					myAdapter.add(poilist.get(i));
				}
			}
			progressDialog.dismiss();
			myAdapter.notifyDataSetChanged();
		}
	};

	private class POIAdapter extends ArrayAdapter<POI> {

		private ArrayList<POI> items;

		public POIAdapter(Context context, int textViewResourceId,
				ArrayList<POI> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.onepoi, null);

			}
			POI poi = items.get(position);
			if (poi != null) {

				TextView tt = (TextView) v.findViewById(R.id.poiname);
				TextView bt = (TextView) v.findViewById(R.id.poimarker);
				ImageView iv = (ImageView) v.findViewById(R.id.poistatus);
				if (tt != null) {
					tt.setText("Flag Name: " + poi.getPOITitle());
				}
				if (bt != null) {
					bt.setText("Marker: " + poi.getMarkerName());
				}
				if (poi.getMarkerPhoneNo().equals(currentPhoneNumber)) {
					v.setBackgroundColor(Color.DKGRAY);
					if (poi.getIsHidden().equals("1")) {
						iv.setImageResource(R.drawable.poi_hidden);
					} else if (poi.getIsHidden().equals("0")) {
						iv.setImageResource(R.drawable.poi_unhidden);
					}
				}
				if (!poi.getMarkerPhoneNo().equals(currentPhoneNumber))
					iv.setImageResource(R.drawable.poi_unhidden);
			}
			return v;
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		boolean supRetVal = super.onCreateOptionsMenu(menu);
		menu.add(1, 0, 0, R.string.refresh_poilist).setIcon(
				R.drawable.refresh);
		menu.add(1, 1, 1, R.string.back_button).setIcon(
				R.drawable.back);
		return supRetVal;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			refreshAdapter();
			return true;
		}
		if (item.getItemId() == 1) {
			this.finish();
			return true;
		}		
		return false;
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		int POIid = (int) ((AdapterView.AdapterContextMenuInfo) menuInfo).id;
		POI clickedPOI = poilist.get(POIid);

		if (clickedPOI.getIsHidden().equals("0")) // unhide
		{
			menu.add(0, R.string.navigate_to_poi, 0, "Navigate");
			menu.add(0, R.string.draw_path_to_poi, 0, "Find path");
		}
		if (clickedPOI.getMarkerPhoneNo().equals(currentPhoneNumber)) {
			if (clickedPOI.getIsHidden().equals("1"))
				menu.add(0, R.string.show_poi, 0, "Show it");
			if (clickedPOI.getIsHidden().equals("0"))
				menu.add(0, R.string.hide_poi, 0, "Hide it");

			menu.add(0, R.string.delete_poi, 0, "Delete it");
		}
		menu.add(0, R.string.view_poi_details, 0, "View details");
		
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int POIid = (int) ((AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo()).id;
		POI clickedPOI = poilist.get(POIid);
		switch (item.getItemId()) {
		// NAVIGATE TO POI
		case R.string.navigate_to_poi:
			setResult(R.string.navigate_to_poi, (new Intent()).putExtra("POIid", clickedPOI
					.getPOIid()));
			finish();
			break;
		case R.string.draw_path_to_poi:
			setResult(R.string.draw_path_to_poi, (new Intent()).putExtra("POIid", clickedPOI
					.getPOIid()));
			finish();
			break;
		case R.string.view_poi_details:

			String name = clickedPOI.getPOITitle() + "'s details";
			String detail = clickedPOI.getAllDetails();
			detail += "*Distance: " + distanceFromMe(clickedPOI.getLocation());
			detail += "\n";
			detailDialog(name, detail);
			break;
		case R.string.hide_poi:
			// clickedPOI.setIsHidden("1");
			HidePOI(clickedPOI.getPOIid());
			progressDialog.show();
			refreshAdapter();
			break;
		case R.string.show_poi:
			// clickedPOI.setIsHidden("0");
			ShowPOI(clickedPOI.getPOIid());
			progressDialog.show();
			refreshAdapter();
			break;
		case R.string.delete_poi:
			// clickedPOI.setIsHidden("0");
			DeletePOI(clickedPOI.getPOIid());
			progressDialog.show();
			refreshAdapter();
			break;
		}
		return super.onContextItemSelected(item);
	}

	private AlertDialog detailDialog(String name, String detail) {
		return (new AlertDialog.Builder(this).setTitle(name).setMessage(detail)
				.show());
	}

	private String distanceFromMe(Location location) {
		final DecimalFormat df = new DecimalFormat("####0.00");
		Location myLocation = locMgr
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		float distance = 0;
		String result = "";
		if (myLocation != null)
			distance = (myLocation.distanceTo(location)) / 1000;
		if (distance < 1) {
			distance = distance * 1000;
			result = df.format(distance) + " meter";
		} else
			result = df.format(distance) + " km";

		return result;
	}

	private void HidePOI(String POIid) {
		JSONObject object = new JSONObject();
		try {
			object.put("POIid", POIid);
			object.put("POIStatus", "hide");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		setPOIStatus.process(object.toString());
	}

	private void ShowPOI(String POIid) {
		JSONObject object = new JSONObject();
		try {
			object.put("POIid", POIid);
			object.put("POIStatus", "show");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		setPOIStatus.process(object.toString());
	}

	private void DeletePOI(String POIid) {
		deletePOI.process(POIid);
	}

	private void refreshAdapter() {
		refreshPOIListHandler.sendMessage(new Message());
	}

	Handler refreshPOIListHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			myAdapter.clear();
			getPOIList();
		}
	};
}
